from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt

@login_required
def index(request):
    return render(request, 'index.html')

@csrf_exempt
def log_in(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return HttpResponseRedirect('/')
    return render(request, 'login.html')

@csrf_exempt
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')

    if request.method == 'POST':
        name = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        user = authenticate(username=name, password=password)
        if user:
            return render(request, 'register.html')

        User.objects.create_user(username=name, email=email, password=password)
        return render(request, 'index.html')

@csrf_exempt
def log_out(request):
    logout(request)
    return HttpResponse('注销成功')
